#! /bin/sh
cd /data/deploy/skywalking || exit 1
BASE_PATH='/data/deploy'
PROJECT_NAME=""
PROJECT_PATH=''
CONTAINER_NAME=""
JAVA_OPTS="-Xms300m -Xmx300m"
PORT=8080
DEBUG_PORT=0
SW_AGENT_NAME=""
SW_AGENT_COLLECTOR_BACKEND_SERVICES=""
while getopts "c:n:d:p:o:a:s:b:" opt; do
    case $opt in
         c)
            CONTAINER_NAME=$OPTARG
          ;;
         n)
            PROJECT_NAME=$OPTARG
          ;;
         d)
            PROJECT_PATH=$OPTARG
          ;;
         p)
            PORT=$OPTARG
          ;;
         o)
            [ -n "$OPTARG" ] && JAVA_OPTS=$OPTARG
          ;;
         a)
            [ -n "$OPTARG" ] && DEBUG_PORT=$OPTARG
          ;;
         s)
            [ -n "$OPTARG" ] && SW_AGENT_NAME=$OPTARG
          ;;
         b)
            [ -n "$OPTARG" ] && SW_AGENT_COLLECTOR_BACKEND_SERVICES=$OPTARG
          ;;
         ?)
            echo "unkonw argument"
            exit 1
          ;;
    esac
done
if [ "$DEBUG_PORT" = "0" ]; then
  JAVA_OPTS=$JAVA_OPTS
else
  JAVA_OPTS="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005"
fi
IMAGE_NAME="${CONTAINER_NAME}:latest"
echo "copy xx.jar from ${BASE_PATH}/${PROJECT_PATH}"
rm -f app.jar
cp ${BASE_PATH}/${PROJECT_PATH}/${PROJECT_NAME}.jar ./app.jar ||  exit 1

echo "begin to build ${PROJECT_NAME} image ！！"

[ -n "`docker ps -a | grep ${CONTAINER_NAME}`" ] && docker rm -f ${CONTAINER_NAME}
[ -n "`docker images | grep ${CONTAINER_NAME}`" ] && docker rmi ${IMAGE_NAME}

docker build -t ${IMAGE_NAME} . || exit 1
echo "${PROJECT_NAME} image build success，java_opts = $JAVA_OPTS ！！^_^"

echo "begin to create container ${CONTAINER_NAME}，port: ${PORT} ！！"

RUN_CMD="docker run -d --name ${CONTAINER_NAME} -p ${PORT}:${PORT} -e JAVA_OPTS=\"${JAVA_OPTS}\" --memory 300m --memory-swap -1 --network hmall ${IMAGE_NAME}"

if [ -n "$SW_AGENT_NAME" ] && [ -n "$SW_AGENT_COLLECTOR_BACKEND_SERVICES" ]; then
  RUN_CMD="${RUN_CMD} -e SW_AGENT_NAME=${SW_AGENT_NAME} -e SW_AGENT_COLLECTOR_BACKEND_SERVICES=${SW_AGENT_COLLECTOR_BACKEND_SERVICES}"
fi

if [ "$DEBUG_PORT" != "0" ]; then
  RUN_CMD="${RUN_CMD} -p ${DEBUG_PORT}:5005"
fi

eval $RUN_CMD || exit 1

echo "container is running now !! ^_^"
exit 0